from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.conf import settings
from vidastream.stream.models import Feed, UserProfile, FeedPrefs
from vidastream.mycache.models import Cache
from vidastream.stream.forms import FeedAddForm, UserProfileForm, FeedPrefsForm
from django import forms
import feedparser, datetime, random, sha, os.path, httplib, urllib2, operator
from pytz import timezone
import pytz
utc = pytz.utc

def uniqify(seq, idfun=None): 
	if idfun is None:
		def idfun(x): return x
	seen = {}
	result = []
	for item in seq:
		marker = idfun(item)
		if marker in seen: continue
		seen[marker] = 1
		result.append(item)
	return result

def convert_time_zones(datetime, new_timezone):
	new_tz = timezone(new_timezone)
	new_dt = new_tz.normalize(datetime.astimezone(new_tz))
	return new_dt

def render_with_request(request, template, context):
	return render_to_response(template, context, context_instance=RequestContext(request))
	

def user_stream(request, username):
	dates_list = []
	feed_date_list = {}
	is_friend = False

	user = User.objects.get(username=username)
	user_profile = user.userprofile_set.get(user=user)

	if request.user.is_authenticated():
		auth_user = User.objects.get(id=request.user.id)
		auth_user_profile = UserProfile.objects.get(user=auth_user)
		if user in auth_user_profile.friends.all():
			is_friend = True 

	if user_profile.hidden:
		if not (request.user in user_profile.friends.all()) and (request.user != user_profile.user):
			raise Http404

	feedlist = Feed.objects.filter(users__id=user.id) 

	for feed in feedlist:
		try:
			feed_prefs = FeedPrefs.objects.get(feed=feed, user=user)
		except FeedPrefs.DoesNotExist:
			pass

		if not feed.disabled:
		# Need to alert the user if a feed has been disabled
			for entry in feed.feedentry_set.all():
				#date = convert_time_zones(entry.updated, "US/Pacific") - datetime.timedelta(hours=3)
				if feed_prefs:
					entry.favicon_url = feed_prefs.get_icon_url
					entry.color = feed_prefs.color

				date = entry.updated
				entry.date = date
				day = datetime.datetime(date.year, date.month, date.day)
				if day in dates_list:
					feed_date_list[day].append(entry)
				else:
					feed_date_list[day] = []
					feed_date_list[day].append(entry)
					dates_list.append(day)

	for day in feed_date_list:
		feed_date_list[day].sort(lambda x, y: cmp(y.date, x.date))

	dates_list.sort()
	day_list = dates_list

	context = {'username': username,
		'feed_date_list': feed_date_list,
		'day_list': day_list,
		'is_friend':is_friend,
		'user_data': user_profile,}

	return render_with_request(request, 'stream/user/stream.html', context)

@login_required
def profile(request):
	context = {}
	return render_with_request(request, 'stream/user/profile.html', context)


@login_required
def user_settings(request):
	return HttpResponseRedirect('/settings/feeds/')
	

@login_required
def user_settings_feeds(request):
	user = User.objects.get(id=request.user.id) 
	fl = request.user.feed_set.all()
	context = {'feeds_list': fl}
	return render_with_request(request, 'stream/user/settings/feeds/index.html', context)

@login_required
def user_settings_feeds_add(request):
	user = User.objects.get(id=request.user.id)
	context = {}

	if request.POST:
		form = FeedAddForm(request.POST)
		if form.is_valid():
			new_feed = Feed.objects.create_feed(form.clean_data['url'], user=user)
			request.user.message_set.create(message="Your feed " + new_feed.title + " was added successfully.")
			return HttpResponseRedirect('/settings/feeds/')
		else:
			context['form'] = form
	else:
		context['form'] = FeedAddForm()

	return render_with_request(request, 'stream/user/settings/feeds/add.html', context)



@login_required
def user_settings_feeds_edit(request, feed_id):
	feed = get_object_or_404(Feed, id=feed_id)
	feed_prefs, created = FeedPrefs.objects.get_or_create(feed=feed, user=request.user)
	context= {'feed': feed}

	if request.POST:
		if request.POST.has_key('action') and request.POST['action'] == "delete":
			request.POST.__delitem__('action')
			feed.users.remove(request.user)
			request.user.message_set.create(message=feed.title + " was deleted successfully.")
			return HttpResponseRedirect('/settings/feeds/')
		else:
			form = FeedPrefsForm(request.POST)
			if form.is_valid():
				feed_prefs = FeedPrefs(id=feed_prefs.id, feed=feed, user=request.user, added=feed_prefs.added, **form.clean_data)
				feed_prefs.save()
				request.user.message_set.create(message="Your feed " + feed.title + " was updated successfully.")
				return HttpResponseRedirect('/settings/feeds/')
			else:
				context['form'] = form
	else:
		context['form'] = FeedPrefsForm(initial=feed_prefs.__dict__)

	return render_with_request(request, 'stream/user/settings/feeds/edit.html', context)


@login_required
def user_settings_feeds_delete(request, feed_id):
	feed = get_object_or_404(Feed, id=feed_id)
	feed_title = feed.title
	feed.users.remove(request.user)
	try:
		feed_prefs = FeedPrefs.objects.get(feed=feed, user=request.user)
	except FeedPrefs.DoesNotExist:
		pass
	else:
		feed_prefs.delete()
		
	request.user.message_set.create(message="Your feed " + feed_title + " was deleted.")
	return HttpResponseRedirect('/settings/feeds/')



@login_required
def user_settings_profile(request):
	user = request.user
	user_profile = UserProfile.objects.get(user=user.id)
	context = {'user_profile': user_profile}

	if request.POST:
		form = UserProfileForm(request.POST)
		if form.is_valid():
			user_profile = UserProfile(id=user_profile.id, user=user, added=user_profile.added, **form.clean_data)
			user_profile.save()
			request.user.message_set.create(message="Your profile has been updated.")
			return HttpResponseRedirect('/settings/profile/')
		else:
			context['form'] = form
	else:
		#context['form'] = UserProfileForm(instance=user_profile)
		context['form'] = UserProfileForm(initial=user_profile.__dict__)
		
	return render_with_request(request, 'stream/user/settings/profile.html', context)


@login_required
def bugreport(request):
	return render_with_request(request, 'stream/bugreport.html', {})


def search(request):
	return render_to_response('stream/search.html', {}, context_instance=RequestContext(request))


@login_required
def friend_control(request, add_or_remove):
	if request.POST:
		user = User.objects.get(id=request.user.id)
		user_profile = UserProfile.objects.get(user=auth_user.id)
		friend_username = request.POST.get('username', None)
		if request.POST.has_key('username'):
			if add_or_remove == "add":
				user_profile.add_friend(username=friend_username)
				request.user.message_set.create(message = '<strong>' + friend_username + "</strong> has been added to your friends list.")

			if add_or_remove == "remove":
				user_profile.remove_friend(username=friend_username)
				request.user.message_set.create(message = '<strong>' + friend_username + "</strong> has been removed from your friends list.")
		else:
			raise Http404
	else:
		raise Http404
			

@login_required
def user_settings_friends(request):
	user = User.objects.get(id=request.user.id)
	user_profile = UserProfile.objects.get(user=user.id)
	friends_list = list(user_profile.friends.all())
	context = {'friends_list': friends_list}
	return render_with_request(request, 'stream/user/settings/friends/index.html', context)

@login_required
def user_settings_friends_add(request):
	if request.POST:
		pass

	return render_with_request(request, 'stream/user/settings/friends/index.html', {})
		
	
@login_required
def user_settings_friends_remove(request, friend_id):
	user = User.objects.get(id=request.user.id)
	user_profile = UserProfile.objects.get(user=auth_user.id)
	user_profile.remove_friend(id=friend_id)

	request.user.message_set.create(message="<strong>" + friend.username + "</strong> is no longer your friend.")
	
	return HttpResponseRedirect("/settings/friends/")
